package com.rapid.maintenance.ui.activity;

import android.view.KeyEvent;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.rapid.maintenance.R;
import com.rapid.maintenance.adapter.MainFragmentAdapter;
import com.rapid.maintenance.base.BaseActivity;
import com.rapid.maintenance.widget.NoScrollViewPager;

import butterknife.BindView;


public class MainActivity extends BaseActivity {

    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    private long firstTime;

    @Override
    protected boolean isUseEventBus() {
        return false;
    }

    @Override
    protected int provideRootLayout() {
        return R.layout.activity_main;
    }

    public void setSelect(int index) {
        TabLayout.Tab tab = tabLayout.getTabAt(index);
        if (tab != null) tab.select();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
                    ToastUtils.showShort("再按一次退出程序");
                    firstTime = secondTime;// 更新firstTime
                    return true;
                } else { // 两次按键小于2秒时，退出应用
                    AppUtils.exitApp();
                    System.exit(0);
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void init() {
        initFragment();
    }

    @Override
    protected boolean hasStatusBar() {
        return false;
    }

    @Override
    protected boolean hasToolBar() {
        return false;
    }

    private void initFragment() {
        //内容适配器，存放fragments实例
        MainFragmentAdapter adapter = new MainFragmentAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(adapter);
        viewPager.setScrollable(false);
        viewPager.setOffscreenPageLimit(adapter.getCount());
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                View v = adapter.getTabView(i);
                tab.setCustomView(v);
            }
        }
    }
}
